<?php
/**
 * 说明.
 * User: dxk <1024114660@qq.com>
 * Date: 2022/4/7
 */
namespace App\Service\OpenApi;

use App\Library\Service\DB\TransactionMonitorService;
use App\Traits\SingleInstanceTrait;

class ApiLogService
{
    use SingleInstanceTrait;

    /**
     * 记录日志
     * @param $log_data
     * @param $code
     * @param $msg
     * @param $data
     * @return bool
     */
    public function log($log_data, $code, $msg, $data): bool
    {
        //执行用时
        $exec_use_time = 0;
        if (defined('START_EXEC_TIME')) {
            $end_exec_time = easy_microtime();
            $exec_use_time = round($end_exec_time - START_EXEC_TIME, 4);
        }
        global $EASY_REQUEST_ID;
        if ($exec_use_time > 1) {
            easy_log('api_long_exec', ['app_key' => $log_data['app_key'], 'request_id' => $EASY_REQUEST_ID, 'method' => $log_data['method'], 'exec_use_time' => $exec_use_time]);
        }
        $log_data['request_id'] = $EASY_REQUEST_ID;
        $log_data['code'] = $code;
        $log_data['msg'] = $msg;
        $log_data['data'] = $data;
        $log_data['ip'] = easy_ip();
        $log_data['exec_use_time'] = $exec_use_time;
        $log_data['created_at'] = date('Y-m-d H:i:s');
        global $SQL_LOG;
        $sql_use_time = 0;
        if (!is_array($SQL_LOG)) $SQL_LOG = [];
        foreach ($SQL_LOG as $item) {
            $sql_use_time += $item['time'];
        }
        $sql_use_time = round($sql_use_time / 1000, 4);
        $log_data['sql_use_time'] = $sql_use_time;
        $api_log = $log_data;
        $api_log['sql_list'] = $SQL_LOG;
        TransactionMonitorService::requestEnd([
            'visit_path' => '接口', 'data' => $log_data,
        ]);
        easy_log('api_log' . DIRECTORY_SEPARATOR . trim($log_data['app_key']), $api_log);
        return true;
    }
}
